<template>
  <div class="box searchBox">
    <van-nav-bar
      right-text="搜索"
      left-arrow
      @click-left="$router.back()"
      @click-right="onSearch"
    >
      <template #title>
        <van-search v-model="value" placeholder="请输入搜索关键词" shape="round" />
      </template>
    </van-nav-bar>
    <div class="searList">
      <div class="hotSearch">
        <h2>热门搜索：</h2>
        <van-tag plain type="primary" @click="onClick('手机')">手机</van-tag>
      </div>
      <div class="hisSearch">
        <h2>搜索历史：</h2>
        <van-tag closeable size="medium" type="primary" @close="close(item)" v-for="item in searchList" :key="item" @click="onClick(item)">
          {{item}}
        </van-tag>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, Search, Tag } from 'vant'
import { addSearch, getSearch, delSearch } from '@/request/index.js'

Vue.use(NavBar)
Vue.use(Search)
Vue.use(Tag)

export default {
  data () {
    return {
      value: '',
      searchList: []
    }
  },
  methods: {
    onSearch () {
      addSearch({
        keyWord: this.value
      }).then(() => {
        this.$router.push('/searchRes?wd=' + this.value)
      })
    },
    close (k) {
      delSearch({
        keyWord: k
      }).then((data) => {
        console.log(data.data)
        this.searchList.splice(this.searchList.indexOf(k), 1)
      })
    },
    onClick (v) {
      addSearch({
        keyWord: v
      }).then(() => {
        this.$router.push('/searchRes?wd=' + v)
      })
    }
  },
  mounted () {
    getSearch().then(data => {
      const arr = []
      data.data.data.forEach(val => {
        arr.push(val.keyWord)
      })
      this.searchList = [...new Set(arr.reverse())]
    })
  }
}
</script>

<style lang="scss">
.searchBox{
  .van-nav-bar__content{
    height: auto;
  }
  .searList{
    background: #efefef;
    height: 100%;
    padding: 0 10px;
    .hotSearch{
      margin-bottom: 0.2rem;
    }
    .van-tag{
      margin: 4px 10px;
      font-size: 16px;
      padding: 6px;
    }
  }
}
</style>
